<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import ElementPlus from 'element-plus'
import EditMenu from './EditMenu.vue'
import { getAdmindata, getMenudatalike, getMenuList,delMenuapi } from '../../api/api'
import data from "@/untils/address/states.json"
const isV3 = ref(false)
let total = ref(0)
let pageSize = ref(10)



//权限管理数据
let permissionquery = ref(true);
let permissionadd = ref(false);
let permissionedit = ref(false);
let permissionremove = ref(false);
let permissionresetPassword = ref(true);

onMounted(() => {
    getMenudata()
    //  try {
    //     // 安全地从 localStorage 获取用户详情
    //     const userDetail = localStorage.getItem("userdetail");
    //     if (!userDetail) {
    //         console.warn("未找到用户详情信息");
    //         return;
    //     }

    //     // 解析用户权限
    //     const { auths } = JSON.parse(userDetail);
    //     if (!auths || !Array.isArray(auths)) {
    //         console.warn("用户权限信息无效");
    //         return;
    //     }

    //     console.log("用户权限列表:", auths);

    //     // 设置权限状态
    //     auths.forEach((item) => {
    //         switch (item) {
    //             case "user:admin:query":
    //                 permissionquery.value = true;
    //                 break;
    //             case "user:admin:add":
    //                 permissionadd.value = true;
    //                 break;
    //             case "user:admin:edit":
    //                 permissionedit.value = true;
    //                 break;
    //             case "user:admin:remove":
    //                 permissionremove.value = true;
    //                 break;
    //             case "user:admin:resetPassword":
    //                 permissionresetPassword.value = true;
    //                 break;
    //         }
    //     });

    //     // 打印最终权限状态
    //     console.log("权限状态:", {
    //         query: permissionquery.value,
    //         add: permissionadd.value,
    //         edit: permissionedit.value,
    //         remove: permissionremove.value,
    //         resetPassword: permissionresetPassword.value
    //     });

    // } catch (error) {
    //     console.error("处理用户权限时出错:", error);
    // }

})

import dayjs from 'dayjs';
import { en } from 'element-plus/es/locales.mjs'
// 定义的头部输入框的数据
let topdata = ref({
    menuName: ""

})
// 表格数据
let tableData = ref([])
async function getMenudata() {
    let res = await getMenuList()
    console.log(res, "router/菜单数据");
    tableData.value = res.data

}


// 渲染状态的显示
let switchFlag = (flag) => {
    return flag ? true : false;
}

// 点击查询
//    async function addschoolbaslike(){
//       console.log(topdata.value);
//       topdata.value.time = dayjs(topdata.value.time).format("YYYY-MM-DD")
//       let {data} = await getschoolbasicslike(topdata.value)
//       console.log(data);
//       if(data.code == 200){
//          tableData.value = data.data
//       }
//    }
// 点击状态按钮 切换状态
//    let chuanflag = ref(0)
// async function switchchange(userId,accountNonLocked){
//     console.log("1",userId,accountNonLocked);

// }
//     async function switchchangeenabled(userId,enabled){
//     console.log("2",userId,enabled);

// }
//    // 删除
let dianjiid = ref(0)
const dialogVisible = ref(false)
function del(val) {
      dianjiid.value = val.menuId
    dialogVisible.value = true
}
async function yesdel() {
    dialogVisible.value = false
      let deldata = await delMenuapi(dianjiid.value)
      if(deldata.code == 200){
         ElMessage({
             message: 'Delete successfully',
             type: 'success',
             })
             getMenudata()
   
      }
}

// 遮罩层
let dialogFormVisible = ref(false)
// 定义 是添加还是编辑的字符串
let changeType = ref("")
// 点击重置密码
// let passwordVisible = ref(false)

// const currentUser = ref({})
// const passwordVisible = ref(false)

// 修改重置密码函数
// function openResetPasswordDialog(user) {
//     console.log(user,currentUser.value);
//     currentUser.value = user
//     passwordVisible.value = true
// }
// 1. 定义表单数据
// const resetForm = ref({
//     newpass: ''
// })
// 确认重置密码
// function reactpass() {
//     passwordVisible.value = false
//      // 如果验证通过 则进行一下环节
//     resetFormRef.value.validate((valid) => {
//         if (valid) {
//             // 验证通过
//             ElMessage.success('密码格式正确')
//             console.log(resetForm.value.newpass);
//             resetForm.value.newpass = ""
//             // 这里可以执行提交操作
//         } else {
//             // 验证失败
//             return false

//         }
//     })
// }

const resetFormRef = ref(null)
const rulesobj = {
    newpass: [
        {
            required: true,
            message: 'Please input a password',
            trigger: 'blur'
        },
        {
            // pattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*])[a-zA-Z\d!@#$%^&*]{8,16}$/,
            pattern: /^(?=.*\d)(?=.*[a-zA-Z])[\da-zA-Z!@#$%^&*]{8,16}$/,
            message: 'Password requires a combination of 8-16 letters, numbers, and special characters',
            trigger: 'blur'
        }
    ]
}

// let refreshTable = ref(true)
// let isExpandAll = ref(true)

// function toggleExpandAll() {
//       refreshTable.value = false
//       isExpandAll.value = !isExpandAll.value
//       nextTick(() => {
//         refreshTable.value = true
//       })
//     }
// 定义 expandRowKeys 来控制展开的行
const expandRowKeys = ref([]); // 存储当前展开的行的 menuId

// 切换展开/折叠状态
const toggleExpandAll = () => {
    if (expandRowKeys.value.length === 0) {
        // 如果当前没有展开的行，则展开所有行
        expandRowKeys.value = tableData.value.map(item => item.menuId);
    } else {
        // 如果当前有展开的行，则折叠所有行
        expandRowKeys.value = [];
    }
};
//  传递参数
let formlist = reactive({})
function add() {
    // tableData.value = []
    Object.assign(formlist, {
        parentId: 0,
        menuType: 1,
        menuName: "",
        icon: "",
        perms: "",
        path: "",
        component: "",
        orderNum: 0,
        type: "新增"
    })
    // console.log(formlist);
    // //  //点击添加按钮
    dialogFormVisible.value = true
    console.log("新增操作");
    changeType.value = 'add'

}
function edit(index, row) {
    console.log("修改", index, row);
    dialogFormVisible.value = true
    //     //用户ID(userId) 昵称、邮箱、手机号、性别(0,1)、区域(国家/洲(省))、地址(非必填)、用户等级(1-5)
    Object.assign(formlist, {
        menuId: row.menuId,
        parentId: row.parentId,
        menuType: row.menuType,
   
        menuName: row.menuName,
        icon: row.icon,
        perms: row.perms,
        path: row.path,
   
        component: row.component,
        orderNum: row.orderNum,
   
        type: "修改"

    })
    //     data.data.forEach(country => {
    //          if (country.state_code == row.area.split("/")[0]) {
    //             console.log("国家:", country.name);
    //             formlist.contry = country.name;
    //             country.states.forEach(st => {
    //                 if (st.state_code == row.area.split("/")[1]) {
    //                     console.log("州:", st.name);
    //                     formlist.addresszhou = st.name;
    //                 }
    //             })
    //         }
    //     });
    //     console.log(formlist.contry, "国家");
    //     console.log(formlist.addresszhou, "州");

    //     console.log(formlist);
    //     console.log(index, row);
    //     //  //点击编辑按钮
    //     //  //把row数据赋值给formlist
    //     // formlist = row
    //     console.log(formlist);

    //     //  //让changeType 标识 为update
    changeType.value = "update"
    //     //  //让dialogFormVisible显示
    dialogFormVisible.value = true
}
//     // 子传父的事件，关闭遮罩层
function closechange() {
    dialogFormVisible.value = false
    // getschoolbas()
    getMenudata()
}
async function menulike() {
    console.log("模糊查询操作");
    console.log(topdata.value);

    let res = await getMenudatalike(topdata.value.menuName)
    console.log(res, "like查询");
    if (res.code == 200) {
        tableData.value = res.data
    }
    // let {nickname,phone,accountNonLocked,enabled} = topdata.value 
    // let res = await getMenudatalike(nickname,phone,accountNonLocked,enabled)
    // console.log(res,"like查询");
    // if(res.code == 200){
    //     tableData.value = res.rows
    // }
}
// 重置操作
function cancel() {
    console.log("重置操作");
    topdata.value = {
        menuName: "",

    }
    getMenudata()
}
// 分页
async function getCurrentPage(e) {
    console.log("获取当前页", e);
    // let res = await getAdmindatapage(e,pageSize.value)
    // console.log(res);
    //  if (res.code == 200) {
    //     tableData.value = res.rows
    // }
}

</script>

<template>
    <div class="administrator">
        <div class="administratorbas">
            <div class="top">
                <span>menu management</span>
            </div>
            <div class="cont">
                <div class="one" v-show="permissionquery">
                    <!-- 输入菜单名称 -->
                    <div class="select">
                        <el-input v-model="topdata.menuName" class="inp" style="width: 240px" placeholder="输入菜单名称">
                            <template #prefix>
                                <el-icon class="el-input__icon">
                                    <search />
                                </el-icon>
                            </template>
                        </el-input>
                    </div>
                    <el-button type="primary" @click="menulike"> 查询</el-button>
                    <el-button type="default" @click="cancel">重置</el-button>
                </div>
                <div class="exp" v-show="permissionadd || permissionquery">
                    <div class="export-excel">
                        <el-button style="width: 100px" type="primary" @click="add()">
                            <el-icon>
                                <FolderAdd />
                            </el-icon><span>新增</span>
                        </el-button>
                        <el-button style="width: 100px" type="primary" @click="toggleExpandAll">
                            <el-icon>
                                <Switch />
                            </el-icon>
                            <span>展开折叠</span>
                        </el-button>
                    </div>
                </div>
                <div class="tab">
                    <!-- <el-table stripe :data="tableData" @selection-change="check()" style="width: 100%;" :fit="true" :empty-text="!permissionquery ? '暂无权限查看' : 'NotData'"  row-key="menuId" v-if="refreshTable" :default-expand-all="isExpandAll"> -->
                    <el-table stripe :data="tableData" @selection-change="check()" style="width: 100%;" :fit="true"
                        :empty-text="!permissionquery ? '暂无权限查看' : 'NotData'" row-key="menuId"
                        :expand-row-keys="expandRowKeys">
                        <el-table-column width="55">
                            <!-- <template #default="scope" @click="check">

                     </template> -->
                        </el-table-column>
                        <el-table-column property="menuName" label="菜单名称" />
                        <el-table-column property="icon" label="图标" />
                        <!-- <el-table-column property="icon" label="图标">
                            <template #default="scope">
                                <component :is="scope.row.icon" style="width: 20px;height: 20px;" />
                            </template>
                        </el-table-column> -->
                        <el-table-column property="icon" label="图标">
                            <template #default="scope">
                                <!-- 使用 <el-icon> 包裹动态组件 -->
                                <el-icon v-if="scope.row.icon">
                                    <component :is="scope.row.icon" />
                                </el-icon>
                            </template>
                        </el-table-column>
                        <el-table-column property="orderNum" label="排序" />
                        <el-table-column property="perms" label="权限管理">
                            <template #default="scope">
                                {{ scope.row.perms ? scope.row.perms : '无' }}
                            </template>
                        </el-table-column>
                        <el-table-column property="component" label="组件路径" />

                        <!-- <el-table-column property="component" label="组件路径">
                            <template #default="scope">
                                <span>{{ scope.row.gender == 1 ? '男' : '女' }}</span>
                            </template>
                        </el-table-column> -->

                        <!-- <el-table-column property="accountNonLocked" label="锁状态">
                            <template #default="scope">
                                <el-switch :modelValue="switchFlag(scope.row.accountNonLocked)" active-text="启用"
                                    inline-prompt inactive-text="禁用" @click="switchchange(scope.row.userId, scope.row.accountNonLocked)"
                                    class="el-switch"  :disabled="!permissionedit ? true : false">
                                </el-switch>
                            </template>
                        </el-table-column> -->
                        <!-- <el-table-column property="enabled" label="启动状态">
                            <template #default="scope">
                                <el-switch :modelValue="switchFlag(scope.row.enabled)" active-text="启用" inline-prompt
                                    inactive-text="禁用" @click="switchchangeenabled(scope.row.userId, scope.row.enabled)"
                                    class="el-switch" :disabled="!permissionedit ? true : false">
                                </el-switch>
                            </template>
                        </el-table-column> -->
                        <!-- <el-table-column property="userLevel" label="用户等级">
                            <template #default="scope">
                                <span>{{ {1: '一', 2: '二', 3: '三', 4: '四', 5: '五'}[scope.row.userLevel] + '级' }}</span>
                            </template>
                        </el-table-column> -->
                        <el-table-column property="name" label="操作" width="300">
                            <template #default="scope">
                                <span class="more-button" @click="edit(scope.$index, scope.row)"
                                    style="cursor: pointer;">
                                    <el-icon size="10">
                                        <EditPen />
                                    </el-icon><span>修改</span>
                                </span>
                                <span class="more-button" @click="del(scope.row)" style="cursor: pointer;">
                                    <el-icon size="10">
                                        <Delete />
                                    </el-icon><span>删除</span>
                                </span>
                                <!-- <el-button type="primary" plain @click="edit(scope.$index, scope.row)">修改</el-button> -->
                                <!-- <el-button type="danger" plain @click=del(scope.row)>删除</el-button> -->
                                <!-- 添加“更多”按钮及下拉菜单 -->
                                <!-- <el-dropdown style="cursor: pointer;">
                                    <span class="more-button">
                                        更多
                                        <el-icon class="el-icon--right"><arrow-down /></el-icon>
                                    </span>
                                    <template #dropdown>
                                        <el-dropdown-menu>
                                            <el-dropdown-item command="resetPassword"
                                                @click="openResetPasswordDialog(scope.row)"> 
                                                {{  permissionresetPassword ? '重置密码' : '无' }}  
                                            </el-dropdown-item>
                                        </el-dropdown-menu>
                                    </template>
            </el-dropdown> -->
                                <!-- <el-dialog v-model="passwordVisible" title="重置密码" width="500" modal-class="custom-modal"
                                    @close="passwordVisible = false">
                                    <span>请输入 {{ currentUser.username }} 的新密码:</span> 
                                    <br>
                                    <el-form :model="resetForm" :rules="rulesobj" ref="resetFormRef">
                                        <el-form-item label="" prop="newpass">
                                            <el-input v-model="resetForm.newpass" type="password" maxlength="16"
                                                minlength="8" auto-complete="off" placeholder="password"></el-input>
                                        </el-form-item>
                                    </el-form>
                                    <template #footer>
                                        <div class="dialog-footer">
                                            <el-button @click="passwordVisible = false">取消</el-button>
                                            <el-button type="primary" @click="reactpass()" >确定</el-button>
                                        </div>
                                    </template>
                                </el-dialog> -->
                            </template>

                        </el-table-column>
                    </el-table>
                    <div style="display: flex;justify-content: end;align-items: center; margin-top: 25px">
                        <el-pagination background layout="prev, pager, next" :page-count="total / pageSize"
                            style="text-align: end;" :current-page='page' @current-change="getCurrentPage" />
                    </div>
                    <el-dialog v-model="dialogVisible" title="删除" width="500">
                        <span>您确定要删除吗</span>
                        <template #footer>
                            <div class="dialog-footer">
                                <el-button @click="dialogVisible = false">取消</el-button>
                                <el-button type="primary" @click="yesdel()">
                                    确定
                                </el-button>
                            </div>
                        </template>
                    </el-dialog>
                </div>
                <EditMenu :dialogFormVisible="dialogFormVisible" :changeType="changeType" v-model:formlist="formlist"
                    @close="closechange"></EditMenu>
                <!-- :formlist="formlist" :changeType="changeType" -->
            </div>
        </div>
    </div>
</template>
<style lang="scss" scoped>
.administrator {
    padding: 15px;
    background-color: #eff1f4;

    .administratorbas {
        background-color: #fff;
        width: 100%;
        height: 88vh;
        border-radius: 10px 10px 0 0;

        .top {
            height: 50px;
            background-color: #f9f9f9;
            border-radius: 10px 10px 0 0;
            font-size: 20px;
            font-weight: bold;
            overflow: hidden;
            border-bottom: 1px solid #f1eded;

            span {
                display: block;
                margin: 10px 0 0 15px;
            }
        }

        .cont {
            .one {
                margin: 10px;
                display: flex;
                padding: 10px;

                div {
                    margin-right: 20px;
                }
            }

            .exp {
                .export-excel {
                    margin-left: 20px;
                }
            }

            .tab {
                margin-top: 20px;
                width: 100%;
                position: relative;
                min-height: 300px;

                .el-table {
                    --el-table-header-bg-color: #fafafa;
                }

                .el-switch {
                    --el-switch-on-color: #45d585;
                }

                .more-button {
                    margin-left: 8px;
                    margin-top: 3px;
                    /* 为“更多”按钮添加左边距 */
                    color: #409EFF;
                    outline: none;

                    /* Element Plus 主题色 */
                    &:hover {
                        color: #66b1ff;

                        /* 鼠标悬停时的颜色 */
                    }
                }
            }
        }
    }

    /* 如果使用 scoped，需要添加 ::v-deep */
    ::v-deep .custom-modal {
        background-color: rgba(0, 0, 0, 0.5);
        /* 设置弹窗背景颜色为半透明 */
    }

    /* 或者更精确的定位 */
    ::v-deep .custom-modal .el-overlay {
        background-color: rgba(0, 0, 0, 0.8);
    }
}
</style>